package com.ordering.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class WebUtils
{
    private static final Logger logger = Logger.getLogger(WebUtils.class);

    /**
     * 获取请求客户端的IP地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request)
    {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String getStringParam(HttpServletRequest request, String pname)
    {
        String value = request.getParameter(pname);
        return StringUtils.isBlank(value) ? "" : value.trim();
    }

    public static int getIntegerParam(HttpServletRequest request, String pname)
    {
        String value = request.getParameter(pname);
        return StringUtils.isBlank(value) ? 0 : Integer.parseInt(value.trim());
    }
    
    /**
     * 异步输出json格式的响应
     * 
     * @param response
     */
    public static  void outJson(String json, HttpServletResponse response)
    {
        PrintWriter out = null;
        try
        {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/json;charset=UTF-8");
            out = response.getWriter();
            out.write(json);
            out.flush();
        }
        catch (Exception e)
        {
            logger.error("输出json字符串异常！", e);
        }
        finally
        {
            if (null != out)
            {
                try
                {
                    out.close();
                }
                catch (Exception e)
                {
                    logger.error("输出json字符串，关闭输出流时异常！");
                }
            }
        }
    }
}
